﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using ICSharpCode.SharpZipLib.Zip;
using static bmapi.Models.ShowModel;

namespace bmapi.Controllers
{
    [Route("style")]
    public class StyleController : PageController
    {
        #region 款式查询
        //款式查询    
        [HttpGet]
        public HttpResponseMessage SelectStyle(int page = 1, int limit = 15, string ModelName = null, string brand = null, string type = null, DateTime? sTime = null, DateTime? eTime = null)
        {

            int loginid = GetCrrentIDByToken();
            if (loginid == 0)
                return AssistFun.toJson(new { status = 201, tip = "工号不存在", data = "" });
            User user = GetUserByLoginID(loginid);

            string sql = "";
            if (ModelName != null)
            {
                sql = string.Format("and (Model_tb.name like '%{0}%' or Style_tb.name like '%{0}%') ", ModelName);
                sql += PingJieCmdForStyle(user.PLID, brand, type, sTime, eTime);
            }
            else
            {
                sql += PingJieCmdForStyle(user.PLID, brand, type, sTime, eTime);
            }
            int totalPage = 0;
            int totalRow = 0;
            string tables = "Style_tb join Model_tb on Style_tb.style_id=Model_tb.style_id";
            string fileds = "Style_tb.name as StyleName,Model_tb.name as ModelName,brand,type,time,state,Style_tb.style_id as StyleId,Style_tb.save_model as SaveModel,Model_tb.id as ModelId";
            try
            {
                //DataTable dt = SQLCommand.GetDataListByPage(tables, fileds, "Style_tb.style_id desc", sql, limit, page, out totalPage, out totalRow);
                DataTable dt = null;
                SQLCommand.GetDataListByPage(tables, fileds, "Style_tb.style_id desc", sql, limit, page, out totalPage, out totalRow,out dt);
                if (dt==null)
                    return AssistFun.toJson(new { status = 201, tip = "暂时没有款式信息", data = "" });
                List<StyleInfo> styleinfo = AssistFun.DataTableToList<StyleInfo>(dt);
                return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = totalRow, rows = styleinfo } });
                    
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new { status = 201, tip = e.Message, data = "" });
            }

        }
        private string PingJieCmdForStyle(int plid, string brand, string type, DateTime? sTime = null, DateTime? eTime = null)
        {
            string sql = "";
            if (plid > 0)
                sql += " and Model_tb.PLID=" + plid;

            if (brand != null)
                sql += string.Format("and brand like '%{0}%'", brand);
            if (type != null)
                sql += string.Format("and type like '%{0}%'", type);
            if (sTime != null)
                sql += "and time>='" + sTime + "'";
            if (eTime != null)
                sql += "and time<='" + eTime + "'";
            return sql;
        }
        #endregion    

        /// <summary>
        /// 款式文件打包下载 
        /// </summary>  
        /// <param name="stylename"></param>
        /// <returns></returns> 
        [HttpGet,Route("downStyle")]
        public HttpResponseMessage DownStyle(int ModelId,string token)
        {
            try
            {
                int loginid = GetCrrentIDByToken(token);
                if(loginid==0)
                    return AssistFun.toJson(new { status = 201, tip ="你无权下载" });
                string stylePath = GetStylePath(ModelId);
                int end = stylePath.LastIndexOf(@"\");
                string name = stylePath.Substring(end + 1);
                string TartgetFile = stylePath.Substring(0, end) + "\\" + name+".zip";

                using (ZipOutputStream ComStream = new ZipOutputStream(File.Create(TartgetFile)))
                {
                    ComStream.SetLevel(6);      //压缩等级
                    if (!Directory.Exists(stylePath))
                        return AssistFun.toJson(new { status = 201, tip = "不存在款式"+name+"的目录" });
                    //压缩文件 有同名压缩文件会自动替换                    
                    ZipFloder(stylePath, ComStream, stylePath);       
                }
                //成功压缩  下载文件 
                return Download(TartgetFile);
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new { status = 201, tip = e.Message });
            }
        }
        ///// <summary>
        ///// 压缩文件夹
        ///// </summary>
        ///// <param name="_OfloderPath"></param>
        ///// <param name="zos"></param>
        ///// <param name="_floderPath"></param>
        //private void ZipFloder(string _OfloderPath, ZipOutputStream zos, string _floderPath)
        //{
        //    foreach (FileSystemInfo item in new DirectoryInfo(_floderPath).GetFileSystemInfos())
        //    {
        //        if (Directory.Exists(item.FullName))
        //        {
        //            ZipFloder(_OfloderPath, zos, item.FullName);
        //        }
        //        else if (File.Exists(item.FullName))//如果是文件  
        //        {
        //            DirectoryInfo ODir = new DirectoryInfo(_OfloderPath);
        //            string fullName2 = new FileInfo(item.FullName).FullName;
        //            string path = ODir.Name + fullName2.Substring(ODir.FullName.Length, fullName2.Length - ODir.FullName.Length);//获取相对目录  
        //            FileStream fs = File.OpenRead(fullName2);
        //            byte[] bts = new byte[fs.Length];
        //            fs.Read(bts, 0, bts.Length);
        //            ZipEntry ze = new ZipEntry(path);
        //            zos.PutNextEntry(ze);             //为压缩文件流提供一个容器  
        //            zos.Write(bts, 0, bts.Length);  //写入字节  
        //        }
        //    }
        //}

        /// <summary>
        /// 修改存储模式  
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPut]
        public HttpResponseMessage UpdateStyle(dynamic obj)
        {
            if (obj == null)
                return AssistFun.toJson(new { status = 201, tip = "请提供修改数据" });
            else
            {
                int styleid = Convert.ToInt32(obj.StyleId);
                int savemodel = Convert.ToInt32(obj.SaveModel);

                string sql = "update Style_tb set save_model=@savemodel where style_id=@styleid";
                SQLCommand sc = new SQLCommand(sql);
                sc.Add("@savemodel",savemodel);
                sc.Add("@styleid",styleid);
                int rtn = sc.ExecuteNonQuery();
                if(rtn==1)
                    return AssistFun.toJson(new { status = 200, tip = "成功" });
                else
                    return AssistFun.toJson(new { status = 201, tip = "失败" });
            }            

        }

    }
}
